/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import JWT from 'jsonwebtoken'
import { permissionSessionKeyName, permissionSessionKey } from '@/config/permissionMap'

import { constantRoutes, resetRouter, addRouters, redirectHome } from '@/router/index'

// 递归处理 每一项的 redirect
function filterRouterListRedirect(router: any[]): any {
  const result: any[] = []
  const _router = router
  _router.forEach((i: any) => {
    if (!i.realPath && i.path[0] === '/' && i.children && i.children[0] && i.children[0].redirect) {
      i.redirect = i.children[0].redirect
    }
    if (i.realPath && i.redirect && i.children && i.children[0]) {
      const childrenPathList = i.children.map((o: any) => `/${o.path}` || '').filter((p: any) => p)
      const _lastPath = i.redirect.replace(i.redirect, '')
      if (!childrenPathList.includes(_lastPath)) {
        i.redirect = `${i.realPath}/${i.children[0].path}`
      }
    }
    if (i.children && i.children.length !== 0) {
      i.children = filterRouterListRedirect(i.children)
    }
    result.push(i)
  })
  return result
}

function filterRouterList(permissionList: string[], router: any[]) {
  const result: any[] = []
  const _router = router
  _router.forEach((i: any) => {
    if (i.permissionKey && !permissionList.includes(i.permissionKey)) {
      return
    }
    if (i.children && i.children.length !== 0) {
      i.children = filterRouterList(permissionList, i.children)
    }
    result.push(i)
  })
  return result
}

function replaceDefaultRedirec(router: any) {
  const _router = router
  let _index = -1
  let _shadowPath = ''
  _router.forEach((i: any, ind: number) => {
    if (i.path === '/') {
      _index = ind
    }
    if (i.permissionKey && i.children && i.children.length !== 0) {
      _shadowPath = i.redirect || i.path
    }
  })
  if (_index !== -1 && _shadowPath !== '') {
    _router[_index].redirect = _shadowPath
  } else if (_index !== -1) {
    _router.splice(_index, 1)
  }
  return _router
}

export function setPermissionRouter(routerPermission: string[], permissionList: any): void {
  // 筛选出有权限的路由list
  let _router = filterRouterList(routerPermission, constantRoutes)
  // 替换 / redirect router
  _router = replaceDefaultRedirec(_router)
  // 匹配相同permissionKey，替换meta - title\icon，增加 _index字段
  _router = matchingReplaceInfo(_router, permissionList)
  // 排序，字段 _index
  _router = sortByIndex(_router)
  // reset router
  resetRouter([])
  // 重置 redirect
  _router = filterRouterListRedirect(_router)
  _router = filterRouterListRedirect(_router)
  // 添加路由
  addRouters(_router)
  // redirect /
  redirectHome()
}

// 处理初始化路由表
export function filterCreateRouterList(): any[] {
  const _sessionData = getSession(permissionSessionKeyName)
  if (!_sessionData) {
    return []
  }
  try {
    const _permission = jwtDecryption(_sessionData, permissionSessionKey)
    // 筛选出有权限的路由list
    let _router = filterRouterList(_permission.routerPermission, constantRoutes)
    // 替换 / redirect router
    _router = replaceDefaultRedirec(_router)
    // 匹配相同permissionKey，替换meta - title\icon，增加 _index字段
    _router = matchingReplaceInfo(_router, _permission.permissionList)
    // 排序，字段 _index
    _router = sortByIndex(_router)
    // 重置 redirect
    _router = filterRouterListRedirect(_router)
    _router = filterRouterListRedirect(_router)
    return _router
  } catch {
    return []
  }
}

// 匹配相同permissionKey，替换meta - title\icon，增加 _index字段
function matchingReplaceInfo(data: any, matchData: any): any {
  data.forEach((i: any) => {
    if (i.permissionKey && matchData[i.permissionKey]) {
      i._index = matchData[i.permissionKey]._index || 0
      if (i.meta && matchData[i.permissionKey].permissionName) {
        i.meta = {
          ...i.meta,
          title: matchData[i.permissionKey].permissionName,
        }
      }
    }
    if (i.children && i.children.length !== 0) {
      i.children = matchingReplaceInfo(i.children, matchData)
    }
  })
  return data
}

// 根据 _index 排序
function sortByIndex(data: any): any {
  data.sort((a: any, b: any) => a._index - b._index)
  data.forEach((i: any) => {
    if (i.children && i.children.length !== 0) {
      i.children = sortByIndex(i.children)
    }
  })
  return data
}

export function getSession(name: string): string {
  if (!name || !window || !window.sessionStorage) {
    return ''
  }
  return window.sessionStorage.getItem(name) || ''
}

function setSession(name: string, value: string) {
  if (!name || !value || !window || !window.sessionStorage) {
    return
  }
  window.sessionStorage.setItem(name, value)
}

function jwtEncryption(t: any, key: string): string {
  if (!t || !key) {
    return ''
  }
  return JWT.sign(t, key)
}

function jwtDecryption(t: string, key: string): any {
  if (!t || !key) {
    return null
  }
  return JWT.verify(t, key)
}

export function savePermissionData(data: any): void {
  setSession(permissionSessionKeyName, jwtEncryption(JSON.stringify(data), permissionSessionKey))
}

export function getCurrentSessionData(sessionName: string): any {
  if (!sessionName) {
    return null
  }
  return jwtDecryption(getSession(sessionName), permissionSessionKey)
}

// 清除 - 权限 sessionStorage
export function clearPermissionSessionData(): void {
  if (!window || !window.sessionStorage) {
    return
  }
  window.sessionStorage.removeItem(permissionSessionKeyName)
}

// 处理全部权限接口数据 - 扁平化
export function flatAllPermissionData(data: any): any {
  let _arr = {}
  data.forEach((i: any, ind: number) => {
    _arr[i.val.permissionCode] = {
      ...i.val,
      _index: ind,
    }
    if (i.children && i.children.length !== 0) {
      _arr = Object.assign(_arr, flatAllPermissionData(i.children))
    }
  })
  return _arr
}

// 处理扁平化后的数据 - 获取权限id list
export function getFlatAllPermissionDataIdList(data: any, type = '1'): any {
  const _arr = []
  for (const key in data) {
    if (data[key].permissionType === type) {
      _arr.push(data[key].permissionCode)
    }
  }
  return _arr
}
